<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="500px" :title="`新增客户`">
    <p></p>
    <el-form ref="ruleFormRef" label-width="150px" label-suffix=" :" :rules="rules" :model="customInfo">
      <el-form-item label="客户姓名" prop="customerName">
        <el-input v-model="customInfo!.customerName" placeholder="请填写客户姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="单位名称" prop="flatsName">
        <el-input v-model="customInfo!.flatsName" placeholder="请填写客户所在单位" clearable></el-input>
      </el-form-item>
      <el-form-item label="身份证号" prop="customerIdentity">
        <el-input v-model="customInfo!.customerIdentity" placeholder="请填写客户身份证号" clearable></el-input>
      </el-form-item>
      <el-form-item label="客户电话" prop="customerPhone">
        <el-input v-model="customInfo!.customerPhone" placeholder="请填写客户电话" clearable></el-input>
      </el-form-item>
      <el-form-item label="收货地址（省）" prop="receiverAddress.province">
        <el-select v-model="customInfo!.receiverAddress!.province" placeholder="请选择省份" @change="onProvinceChange">
          <el-option v-for="province in provinceList" :key="province" :label="province" :value="province"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收货地址（市）" prop="receiverAddress.city">
        <el-select v-model="customInfo!.receiverAddress!.city" placeholder="请选择城市" @change="onCityChange">
          <el-option v-for="city in cityList" :key="city" :label="city" :value="city"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收货地址（区）" prop="receiverAddress.zone">
        <el-select v-model="customInfo!.receiverAddress!.zone" placeholder="请选择区县">
          <el-option v-for="district in districtList" :key="district" :label="district" :value="district"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址" prop="receiverAddress.detail">
        <el-input v-model="customInfo!.receiverAddress!.detail" placeholder="请填写客户详细地址" clearable></el-input>
      </el-form-item>
      <el-form-item label="邮件地址" prop="customerEmail">
        <el-input v-model="customInfo!.customerEmail" placeholder="请填写客户邮箱" clearable></el-input>
      </el-form-item>
      <el-form-item label="座机号" prop="customerLandline">
        <el-input v-model="customInfo!.customerLandline" placeholder="请填写客户座机" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="tsx" name="UserDrawer">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { addCustom } from "@/api/modules/custom";
import axios from "axios";
import { Custom } from "@/api/interface";

const rules = reactive({
  customerName: [
    { required: true, message: "请填写客户姓名" },
    { pattern: /^[\u4e00-\u9fa5]{2,4}$/, message: "姓名格式不正确" }
  ],
  flatsName: [{ required: true, message: "请填写客户所在单位" }],
  customerIdentity: [
    { required: true, message: "请填写客户身份证号" },
    { pattern: /^\d{17}[\dXx]$/, message: "身份证号格式不正确" }
  ],
  customerPhone: [
    { required: true, message: "请填写客户电话" },
    { pattern: /^1[3-9]\d{9}$/, message: "电话号格式不正确" }
  ],
  "receiverAddress.province": [{ required: true, message: "请填写省份" }],
  "receiverAddress.city": [{ required: true, message: "请填写城市" }],
  "receiverAddress.zone": [{ required: true, message: "请填写地区" }],
  "receiverAddress.detail": [{ required: true, message: "请填写详细地址" }],
  customerEmail: [{ required: true, message: "请填写客户邮箱" }],
  customerLandline: [{ required: true, message: "请填写客户座机" }]
});

interface DrawerProps {
  title?: string;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerProps = ref<DrawerProps>({
  title: "新增客户"
});
const drawerVisible = ref(false);

const customInfo = ref<Partial<Custom.CustomEntity>>({
  customerName: "",
  flatsName: "",
  customerIdentity: "",
  customerPhone: "",
  receiverAddress: {
    province: "",
    city: "",
    zone: "",
    detail: ""
  },
  customerEmail: "",
  customerLandline: ""
});

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  console.log(drawerProps.value);
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await addCustom(customInfo.value);
      ElMessage.success({ message: `${customInfo.value.customerName}添加成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

const provinceList = ref([]);
const cityList = ref([]);
const districtList = ref([]);

const fetchProvinces = async () => {
  try {
    const response = await axios.get(
      "https://restapi.amap.com/v3/config/district?keywords=中国&subdistrict=1&key=7d36a7cce58b0b66bb018cc58cf3498f"
    );
    const provinces = response.data?.districts[0]?.districts || [];
    provinceList.value = provinces.map((province: any) => province.name);
  } catch (error) {
    console.error(error);
  }
};

const fetchCities = async (province: string) => {
  try {
    const response = await axios.get(
      `https://restapi.amap.com/v3/config/district?keywords=${province}&subdistrict=1&key=7d36a7cce58b0b66bb018cc58cf3498f`
    );
    const cities = response.data?.districts[0]?.districts || [];
    cityList.value = cities.map((city: any) => city.name);
  } catch (error) {
    console.error(error);
  }
};

const fetchDistricts = async (city: string) => {
  try {
    const response = await axios.get(
      `https://restapi.amap.com/v3/config/district?keywords=${city}&subdistrict=1&key=7d36a7cce58b0b66bb018cc58cf3498f`
    );
    const districts = response.data?.districts[0]?.districts || [];
    districtList.value = districts.map((district: any) => district.name);
  } catch (error) {
    console.error(error);
  }
};

const onProvinceChange = (province: string) => {
  customInfo!.value.receiverAddress!.city = "";
  customInfo!.value.receiverAddress!.zone = "";
  fetchCities(province);
};

const onCityChange = (city: string) => {
  customInfo!.value.receiverAddress!.zone = "";
  fetchDistricts(city);
};

onMounted(() => {
  fetchProvinces();
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

defineExpose({
  acceptParams
});
</script>
